package com.smedi.ismedi.progress.core.port.adapter.persistence.repository.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.constructionproject.api.dto.response.ProjectBasicResponse;
import com.smedi.ismedi.progress.api.dto.response.FileResponse;
import com.smedi.ismedi.progress.core.application.command.ProcessListQuery;
import com.smedi.ismedi.progress.core.application.command.ProgressKanBanQuery;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.*;
import com.smedi.ismedi.progress.core.domain.dto.FileQuery;
import com.smedi.ismedi.progress.core.domain.dto.PersonQuery;
import com.smedi.ismedi.progress.core.domain.dto.ProjectQuery;
import com.smedi.ismedi.progress.core.domain.dto.VersionManageQuery;
import com.smedi.ismedi.progress.core.domain.repository.*;
import com.smedi.ismedi.progress.api.dto.response.ProgressKanBanStatisticResponse;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.Progress;
import com.smedi.ismedi.progress.core.domain.repository.FileRepository;
import com.smedi.ismedi.progress.core.domain.repository.ProgressProjectRepository;
import com.smedi.ismedi.progress.core.domain.repository.ProgressRepository;
import com.smedi.ismedi.progress.core.infrastructure.constant.EngieerStatusEnum;
import com.smedi.ismedi.progress.core.infrastructure.util.Pager;
import com.smedi.ismedi.progress.core.port.adapter.convert.AdapterConverter;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.*;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.*;
import com.smedi.ismedi.progress.core.port.adapter.service.ProcessRemoteService;
import com.smedi.ismedi.web.starter.common.ResponseData;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.*;

/**
 * 进度计划仓库实现类
 *
 * @author liaojiajie
 * @date 2022/9/21
 */
@Repository
@AllArgsConstructor
@Slf4j
public class ProgressRepositoryImpl implements ProgressRepository {
    private final AdapterConverter adapterConverter;
    private final FileRepository fileRepository;
    private final AuthorityUtil authorityUtil;
    private final ProgressMapper progressMapper;
    private final ProgressProjectRepository progressProjectRepository;
    private final VersionManageMapper versionManageMapper;
    private final ProjectRepository projectRepository;
    private final PersonRepository personRepository;
    private final VersionDetailMapper versionDetailMapper;
    private final ProjectScheduleDetaillMapper projectScheduleDetaillMapper;
    private final ProjectAttachmentImageMapper projectAttachmentImageMapper;
    private final ProcessRemoteService processRemoteService;
    private final ProgressDetailMapper progressDetailMapper;



    @Override
    public Page<Progress> getProgressPage(Long offset, Long pageSize, Long hrOrganizationId, Integer projectId, String projectManager, Integer mainCourtyardId, Integer status, String projectCategory) {
        Page<ProgressEntity> progressEntity = new Page<>(offset, pageSize);
        ResponseData<List<ProjectBasicResponse>> projectList = new ResponseData<>();
        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Long> ids = new ArrayList<>();
        List<ProjectBasicResponse> projectListData = new ArrayList<>();
        //主体院条件选择   选了则传主体院id查项目
        if (mainCourtyardId == null) {
            projectList = progressProjectRepository.getProjectList(hrOrganizationId);
        }
        if (mainCourtyardId != null) {
            projectList = progressProjectRepository.getProjectList(mainCourtyardId.longValue());
        }
        List<ProjectBasicResponse> data = projectList.getData();
        //项目列表不为空 筛选ids
        if(data != null){
            projectListData = data.stream().filter(v -> {
                if (StringUtils.isNotBlank(projectCategory)) {
                    return projectCategory.equals(v.getProjectCategory());
                }
                return true;
            }).filter(v -> {
                if (StringUtils.isNotBlank(projectManager)) {
                    return v.getProjectManager().indexOf(projectManager) > -1;
                }
                return true;
            }).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(projectListData)){
                ids =projectListData.stream().map(ProjectBasicResponse::getProjectId).collect(Collectors.toList());
            }
        }
        //如果企业组织id下没有项目   则没有项目计划
        if (hrOrganizationId !=null && CollectionUtils.isEmpty(projectListData)){
            return new Page<>();
        }
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(ids), ProgressEntity::getProjectId, ids);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(projectId), ProgressEntity::getProjectId, projectId);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(status), ProgressEntity::getProgressStatus, status);

        lambdaQueryWrapper.orderByAsc(ProgressEntity::getProgressStatus);
        lambdaQueryWrapper.orderByDesc(ProgressEntity::getSubmitTime);
        Page<ProgressEntity> progressEntityPage = progressMapper.selectPage(progressEntity, lambdaQueryWrapper);
        List<ProjectBasicResponse> List = projectListData;
        if (hrOrganizationId != null && List.size()>0) {
            progressEntityPage.getRecords().forEach(v -> {
                for (ProjectBasicResponse projectBasicResponse: List){
                    if (v.getProjectId().equals(projectBasicResponse.getProjectId())) {
                        v.setName(projectBasicResponse.getProjectName());
                        v.setEngineerType(projectBasicResponse.getProjectCategory());
                        v.setGeneralManager(projectBasicResponse.getProjectManager());
                    }
                }
            });
        }

        //app端 项目视角
       else if (hrOrganizationId == null && CollectionUtils.isEmpty(data)){
           ProjectBasicResponse project = progressProjectRepository.getProject(projectId.longValue());
            progressEntityPage.getRecords().forEach(v -> {
                v.setName(project.getProjectName());
                v.setEngineerType(project.getProjectCategory());
                v.setGeneralManager(project.getProjectManager());
            });
        }

        //判断未完成的任务是否有滞后，有滞后，那么此项目就滞后
        progressEntityPage.getRecords().forEach(v -> {
            LambdaQueryWrapper<ProgressDetailEntity> detailEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            detailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectScheduleId,v.getId());
            detailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectId,v.getProjectId());
            //detailEntityLambdaQueryWrapper.like(ProgressDetailEntity ::getType,"1");
            detailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getCompletion,0);
            detailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getStatus,0);
            List<ProgressDetailEntity> detailEntityList = progressDetailMapper.selectList(detailEntityLambdaQueryWrapper);
            if(detailEntityList.size()>0){
                v.setProgressStatus(0);
            }else{
                v.setProgressStatus(1);
            }
            LambdaQueryWrapper<VersionManageEntity> versionManageEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getProjectId,v.getProjectId());
            versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getStatus,1);
            versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getMainCourtyardApproval,2);
            VersionManageEntity versionManageEntity = versionManageMapper.selectOne(versionManageEntityLambdaQueryWrapper);
            v.setVersion(versionManageEntity.getVersion());
        });
        Page<Progress> progressPage = adapterConverter.progressEntityPageToProgress(progressEntityPage);

        return progressPage;

    }

    @Override
    public Page<Progress> getProgressPageByApp(Long offset, Long pageSize, Long hrOrganizationId,Integer projectId, String appSearch, Integer progressStatus) {
        Page<ProgressEntity> progressEntity = new Page<>(offset, pageSize);
        ResponseData<List<ProjectBasicResponse>> projectList = new ResponseData<>();
        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Long> ids = new ArrayList<>();
        List<ProjectBasicResponse> projectListData = new ArrayList<>();
        if(hrOrganizationId != null){
            projectList = progressProjectRepository.getProjectList(hrOrganizationId);
            //如果企业组织id下没有项目   则没有项目计划
            if (CollectionUtils.isEmpty(projectList)){
                return new Page<>();
            }
            List<ProjectBasicResponse> data = projectList.getData();
            //项目列表不为空 筛选ids
            if(data != null){
                projectListData = data.stream().collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(projectListData)){
                    projectListData.forEach(v ->{
                        ids.add(v.getProjectId());
                    });
                }
            }
        }

        List<Long> appSearchProjectIds = new ArrayList<>();
        /*if(ObjectUtils.isNotNull(appSearch)){
            List<ProjectBasicResponse> projects = progressProjectRepository.getProjectListByApp(appSearch,ids).getData();
            projects.forEach(v ->{
                appSearchProjectIds.add(v.getProjectId());
            });
        }
        if(ids.size() > 0 && appSearchProjectIds.size() > 0){
            lambdaQueryWrapper.in( ProgressEntity::getProjectId, appSearchProjectIds);
            lambdaQueryWrapper.in( ProgressEntity::getProjectId, ids);
        }else if(appSearchProjectIds.size() == 0 && ObjectUtils.isNotNull(appSearch)){
            return new Page<>();
        }else if(appSearchProjectIds.size() > 0){
            lambdaQueryWrapper.in(ProgressEntity::getProjectId, appSearchProjectIds);
        }else{

        }*/
        if(ObjectUtils.isNotNull(progressStatus)){
            if(progressStatus == 2){
                //待审核
                List<Long> versionProjectIds = new ArrayList<>();
                LambdaQueryWrapper<VersionManageEntity> versionManageEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
                versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getMainCourtyardApproval,1);
                List<VersionManageEntity> versionManageEntities = versionManageMapper.selectList(versionManageEntityLambdaQueryWrapper);
                versionManageEntities.forEach(v->{
                    versionProjectIds.add(v.getProjectId());
                });
                if(CollectionUtils.isNotEmpty(versionProjectIds)){
                    lambdaQueryWrapper.in(ProgressEntity::getProjectId, versionProjectIds);
                }else{
                    return new Page<>();
                }

            }else{
                lambdaQueryWrapper.eq(ProgressEntity::getProgressStatus, progressStatus);
            }
        }

        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(projectId), ProgressEntity::getProjectId, projectId);
        //2024-07-30 修改根据项目名/项目经理名称查询不到数据的BUG
        lambdaQueryWrapper.in(ObjectUtils.isNotNull(ids),ProgressEntity::getProjectId, ids);
        if(ObjectUtils.isNotNull(appSearch)){
            lambdaQueryWrapper.and(wrapper->wrapper.like(ProgressEntity ::getName,appSearch).or().like(ProgressEntity ::getGeneralManager,appSearch));
        }
        lambdaQueryWrapper.orderByAsc(ProgressEntity::getProgressStatus);
        lambdaQueryWrapper.orderByDesc(ProgressEntity::getSubmitTime);
        Page<ProgressEntity> progressEntityPage = progressMapper.selectPage(progressEntity, lambdaQueryWrapper);


        progressEntityPage.getRecords().forEach(v -> {
            ProjectBasicResponse project = progressProjectRepository.getProject(v.getProjectId());
            v.setName(project.getProjectName());
            v.setEngineerType(project.getProjectCategory());
            v.setGeneralManager(project.getProjectManager());
            v.setHrOrganizationFullName(project.getHrOrganizationFullName());
            LambdaQueryWrapper<VersionManageEntity> versionManageEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getMainCourtyardApproval,1);
            versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getProjectId,v.getProjectId());
            versionManageEntityLambdaQueryWrapper.orderByDesc(VersionManageEntity ::getVersion);
            List<VersionManageEntity> versionManageEntities = versionManageMapper.selectList(versionManageEntityLambdaQueryWrapper);
            if(versionManageEntities.size() > 0){
                v.setMainCourtyardApproval(1);
                v.setVersionId(versionManageEntities.get(0).getId());
            }else{
                versionManageEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
                versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getMainCourtyardApproval,2);
                versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getStatus,1);
                versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getProjectId,v.getProjectId());
                VersionManageEntity versionManageEntity = versionManageMapper.selectOne(versionManageEntityLambdaQueryWrapper);
                if(versionManageEntity != null){
                    v.setVersionId(versionManageEntity.getId());
                    v.setVersion(versionManageEntity.getVersion());
                }
                v.setMainCourtyardApproval(2);
            }
        });
        Page<Progress> progressPage = adapterConverter.progressEntityPageToProgress(progressEntityPage);
        progressPage.getRecords().forEach(v->{
            List<Person> persons;
            persons = personRepository.getPersonList(PersonQuery.builder().projectJob("施工项目经理").projectId(v.getProjectId()).build());
            List<Long> personIds = persons.stream().distinct().map(Person::getId).collect(Collectors.toList());
            v.setConstructionMember(personIds);
        });
        return progressPage;
    }

    @Override
    public Progress getVersionManageOne(VersionManageQuery versionManageQuery) {
        LambdaQueryWrapper<VersionManageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(versionManageQuery.getId()), VersionManageEntity::getId, versionManageQuery.getId());
        VersionManageEntity versionManageEntity = versionManageMapper.selectOne(lambdaQueryWrapper);
        return this.extend(versionManageEntity);
    }

    @Override
    @Transactional
    public void selectAndUpdate(Progress versionManage, ProjectBasicResponse projectData) {
        versionManageMapper.updateVersionManage(versionManage.getProjectId());
        List<ProgressDetailEntity> insterProgressDetail = new ArrayList<>();
        // 查询版本表中项目详情
        LambdaQueryWrapper<VersionDetailEntity> lambdaQueryWrapper7 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper7.eq(ObjectUtils.isNotNull(versionManage.getProjectId()), VersionDetailEntity::getProjectId, versionManage.getProjectId());
        lambdaQueryWrapper7.eq(ObjectUtils.isNotNull(versionManage.getId()), VersionDetailEntity::getVersionManageId, versionManage.getId());
        List<VersionDetailEntity> versionDetailListsnew = versionDetailMapper.selectList(lambdaQueryWrapper7);
        // 更新项目总表中是否存在对应的项目数据 然后更新 计划开始时间（取任务计划开始时间最小值）、计划完成时间（取任务计划完成时间最大值）、里程碑数量、关键任务数量、版本号
//        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper4 = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper4.eq(ObjectUtils.isNotNull(versionManage.getProjectId()), ProgressEntity::getProjectId, versionManage.getProjectId());
//        // 查询项目
//        ProgressEntity progressEntity = progressMapper.selectOne(lambdaQueryWrapper4);
//        versionManageMapper.updateVersionManage(versionManage.getProjectId());
//        // 根据项目id 查询对应的项目中是否存在对应的数据无插入 有更新
//        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper5.eq(ObjectUtils.isNotNull(versionManage.getProjectId()), ProgressEntity::getProjectId, versionManage.getProjectId());
//        LambdaQueryWrapper<ProgressDetailEntity> lambdaQueryWrapper6 = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper6.eq(ObjectUtils.isNotNull(versionManage.getProjectId()), ProgressDetailEntity::getProjectId, versionManage.getProjectId());
//        // 查询项目
//        Integer projectCount = progressMapper.selectCount(lambdaQueryWrapper5);
//        // 查询项目详情
//        Integer projectDetailCount = projectScheduleDetaillMapper.selectCount(lambdaQueryWrapper6);
        ProgressEntity progressEntity = progressMapper.findProject(versionManage.getProjectId());
        // 查找版本项目详情表中 计划开始时间（取任务计划开始时间最小值）
        VersionDetail versionDetail = versionDetailMapper.findScheduleStartTimeMax(versionManage.getProjectId(), versionManage.getVersion(), versionManage.getId());
//        if (projectCount == 0 && projectDetailCount == 0) {
          if (progressEntity == null) {
            // 插入项目表\ 插入详情表
//            ProjectBasicResponse projectData = progressProjectRepository.getProject(versionManage.getProjectId());
            ProgressEntity projectDateil = new ProgressEntity();

            if (projectData != null){
                projectDateil.setProjectId(projectData.getProjectId());
                projectDateil.setName(projectData.getProjectName());
                projectDateil.setEngineerType(projectData.getProjectCategoryMeaning());
                projectDateil.setGeneralManager(projectData.getProjectManager());
            }
            projectDateil.setConstructManager(versionManage.getConstructManager());//  先写死接口中没有
            projectDateil.setSubmitTime(LocalDateTime.now());
            if (versionDetail != null){
                projectDateil.setScheduleStartTime(versionDetail.getScheduleStartTime());
                projectDateil.setScheduleEndTime(versionDetail.getScheduleEndTime());
                projectDateil.setVersion(versionDetail.getVersion());
                projectDateil.setMilestoneNums(versionDetail.getMilestoneNums());
                projectDateil.setKeyTaskNums(versionDetail.getKeyTaskNums());
            }
            projectDateil.setCreatedDate(LocalDateTime.now());
            projectDateil.setCreatedUserId(authorityUtil.getPersonId());
              //版本号 取传过来的
            projectDateil.setVersion(versionManage.getVersion().intValue());
            progressMapper.insertProject(projectDateil);
            LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper41 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper41.eq(ObjectUtils.isNotNull(versionManage.getProjectId()), ProgressEntity::getProjectId, versionManage.getProjectId());
            // 查询项目
            ProgressEntity progressEntity1 = progressMapper.selectOne(lambdaQueryWrapper41);
            // 查询版本表中项目详情
//            LambdaQueryWrapper<VersionDetailEntity> lambdaQueryWrapper7 = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper7.eq(ObjectUtils.isNotNull(versionManage.getProjectId()), VersionDetailEntity::getProjectId, versionManage.getProjectId());
//            lambdaQueryWrapper7.eq(ObjectUtils.isNotNull(versionManage.getId()), VersionDetailEntity::getVersionManageId, versionManage.getId());
//            List<VersionDetailEntity> versionDetailListsnew = versionDetailMapper.selectList(lambdaQueryWrapper7);
            versionDetailListsnew.forEach(b -> {
                ProgressDetailEntity progressDetail2 = adapterConverter.bToProgressDetailEntity(b);
                progressDetail2.setProjectScheduleId(progressEntity1.getId());
                progressDetail2.setCreatedDate(LocalDateTime.now());
                progressDetail2.setCreatedUserId(authorityUtil.getPersonId());
                progressDetail2.setScheduleDuration(b.getSchduleDuration().intValue());
                progressDetail2.setVersion(b.getVersion().intValue());
                progressDetail2.setNamePrefix(b.getNamePrefix());
                progressDetail2.setId(b.getId());
                progressDetail2.setParentId(b.getParentId());
                progressDetail2.setParentName(b.getParentName());
                progressDetail2.setSortIndex(b.getSortIndex());
                insterProgressDetail.add(progressDetail2);
            });
            if (!insterProgressDetail.isEmpty()){
                projectScheduleDetaillMapper.insertScheduleDetaillBatch(insterProgressDetail);
            }
        } else {
            // 更新主表
            versionDetail.setLatestUpdatedDate(LocalDateTime.now());
            versionDetail.setLatestUpdatedUserId(authorityUtil.getPersonId());
            progressMapper.updateData(versionDetail);
            /*更新项目详情表中  (任务/里程碑)名称、类型(0、里程碑 1、关键任务  3、其他)、计划开始时间、计划完成时间、计划工期、负责人、版本号
        还需判断里程碑中是否有新增如果有新增需要重新添加，不存在需要删除。*/
//            LambdaQueryWrapper<VersionDetailEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(versionManage.getId()), VersionDetailEntity::getVersionManageId, versionManage.getId());
//            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(versionManage.getProjectId()), VersionDetailEntity::getProjectId, versionManage.getProjectId());
//            List<VersionDetailEntity> versionDetailLists = versionDetailMapper.selectList(lambdaQueryWrapper1);
            LambdaQueryWrapper<ProgressDetailEntity> progressDetail = new LambdaQueryWrapper<>();
            progressDetail.eq(ObjectUtils.isNotNull(versionManage.getProjectId()), ProgressDetailEntity::getProjectId, versionManage.getProjectId());
            List<ProgressDetailEntity> progressDetails = projectScheduleDetaillMapper.selectList(progressDetail);
            // 不存在插入
            List<VersionDetailEntity> versiondetailList = versionDetailListsnew.stream().filter(versionDetailList ->!progressDetails.stream().anyMatch(proDetail->(versionDetailList.getName().equals(proDetail.getName()) && versionDetailList.getParentName().equals(proDetail.getParentName())))).collect(Collectors.toList());
            if (!versiondetailList.isEmpty()){
                versiondetailList.forEach(deatilProgrss->{
                    ProgressDetailEntity progressDetail2 = adapterConverter.bToProgressDetailEntity(deatilProgrss);
                    progressDetail2.setProjectScheduleId(progressEntity.getId());
                    progressDetail2.setCreatedDate(LocalDateTime.now());
                    progressDetail2.setCreatedUserId(authorityUtil.getPersonId());
                    progressDetail2.setScheduleDuration(deatilProgrss.getSchduleDuration().intValue());
                    progressDetail2.setVersion(deatilProgrss.getVersion().intValue());
                    progressDetail2.setNamePrefix(deatilProgrss.getNamePrefix());
                    progressDetail2.setSortIndex(deatilProgrss.getSortIndex());
//                    progressDetail2.setId(deatilProgrss.getId());
//                    progressDetail2.setParentId(deatilProgrss.getParentId());
//                    progressDetail2.setParentName(deatilProgrss.getParentName());
                    insterProgressDetail.add(progressDetail2);
                });
                if (!insterProgressDetail.isEmpty()){
                    projectScheduleDetaillMapper.insertScheduleDetaillBatch(insterProgressDetail);
                }
            }
            // 多余删除
            List<ProgressDetailEntity> progressDetailList = progressDetails.stream().filter(versionDetailList ->!versionDetailListsnew.stream().anyMatch(proDetail->(versionDetailList.getName().equals(proDetail.getName()) && versionDetailList.getParentName().equals(proDetail.getParentName())))).collect(Collectors.toList());
            List<ProjectAttachmentImageEntity> projectAttachmentImageList = new ArrayList<>();
            if (!progressDetailList.isEmpty()){
                // 处理对应的图片数据
                progressDetailList.forEach(image->{
                    // 查询对应的图片信息
                    LambdaQueryWrapper<ProjectAttachmentImageEntity> projectAttachmentImageEntity = new LambdaQueryWrapper<>();
                    projectAttachmentImageEntity.eq(ObjectUtils.isNotNull(image.getId()), ProjectAttachmentImageEntity::getProjectScheduleDetailId, image.getId());
                    List<ProjectAttachmentImageEntity> projectAttachmentImages = projectAttachmentImageMapper.selectList(projectAttachmentImageEntity);
                    projectAttachmentImageList.addAll(projectAttachmentImages);
                });
                projectScheduleDetaillMapper.deleteScheduleDetaillBatch(progressDetailList);
            }
            if (!projectAttachmentImageList.isEmpty()){
                projectAttachmentImageMapper.deleteBatch(projectAttachmentImageList);
            }
            List<ProjectScheduleDetailPart> ProjectScheduleDetailPart = new ArrayList<>();
            // 存在更新
            List<VersionDetailEntity> versiondetailLists = versionDetailListsnew.stream().filter(versionDetailList ->progressDetails.stream().anyMatch(proDetail->(versionDetailList.getName().equals(proDetail.getName()) && versionDetailList.getParentName().equals(proDetail.getParentName())))).collect(Collectors.toList());
                versiondetailLists.forEach(v->{
                    ProjectScheduleDetailPart progressDetail2 = new ProjectScheduleDetailPart();
                    // 更新项目详情
                    progressDetail2.setScheduleDuration(v.getSchduleDuration().intValue());
                    progressDetail2.setName(v.getName());
                    progressDetail2.setNamePrefix(v.getNamePrefix());
                    progressDetail2.setParentId(v.getParentId());
                    progressDetail2.setResponsiblePerson(v.getResponsiblePerson());
                    progressDetail2.setType(v.getType());
                    progressDetail2.setScheduleStartTime(v.getScheduleStartTime());
                    progressDetail2.setScheduleEndTime(v.getScheduleEndTime());
                    progressDetail2.setLatestUpdatedDate(LocalDateTime.now());
                    progressDetail2.setLatestUpdatedUserId(authorityUtil.getPersonId());
                    progressDetail2.setProjectId(v.getProjectId());
                    progressDetail2.setVersion(v.getVersion());
                    progressDetail2.setParentId(v.getParentId());
                    progressDetail2.setParentName(v.getParentName());
                    progressDetail2.setId(v.getId());
                    progressDetail2.setSortIndex(v.getSortIndex());
                    // 查询对应的图片信息
                    LambdaQueryWrapper<ProgressDetailEntity> progressDetailEntity = new LambdaQueryWrapper<>();
                    progressDetailEntity.eq(ObjectUtils.isNotNull(v.getName()), ProgressDetailEntity::getName, v.getName());
                    progressDetailEntity.eq(ObjectUtils.isNotNull(v.getParentName()), ProgressDetailEntity::getParentName, v.getParentName());
                    progressDetailEntity.eq(ObjectUtils.isNotNull(v.getProjectId()), ProgressDetailEntity::getProjectId, v.getProjectId());
                    List<ProgressDetailEntity> progressDetailss = projectScheduleDetaillMapper.selectList(progressDetailEntity);
                    List<Long> ids = progressDetailss.stream().distinct().map(x ->x.getId()).collect(Collectors.toList());
                    // 查询图片信息
                    LambdaQueryWrapper<ProjectAttachmentImageEntity> projectAttachmentImageEntity = new LambdaQueryWrapper<>();
                    projectAttachmentImageEntity.in(ObjectUtils.isNotNull(ids),ProjectAttachmentImageEntity::getProjectScheduleDetailId,ids);
                    List<ProjectAttachmentImageEntity> projectAttachmentImages = projectAttachmentImageMapper.selectList(projectAttachmentImageEntity);
                    projectAttachmentImages.forEach(m->{
                        ProjectAttachmentImageEntity imagedd = adapterConverter.mdToProjectAttachmentImageEntity(m);
                        imagedd.setProjectScheduleDetailId(v.getId());
                        QueryWrapper<ProjectAttachmentImageEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("id", m.getId());
                        queryWrapper.eq("project_schedule_detail_id", m.getProjectScheduleDetailId());
                        projectAttachmentImageMapper.update(imagedd, queryWrapper);
                    });
//                    projectScheduleDetaillMapper.updateData(progressDetail2);
                    ProjectScheduleDetailPart.add(progressDetail2);
                });
                if (!ProjectScheduleDetailPart.isEmpty()){
                    projectScheduleDetaillMapper.updateData(ProjectScheduleDetailPart);
                }
        }
    }

    @Override
    public Progress saveVersionManage(Progress versionManage) {
        VersionManageEntity versionManageEntity = adapterConverter.ProgressToVersionManageEntity(versionManage);
        versionManageEntity.setSubmitTime(LocalDateTime.now());
        if (ObjectUtils.isNull(versionManageEntity.getId())) {
            versionManageMapper.insert(versionManageEntity);
        }
        if (ObjectUtils.isNotNull(versionManageEntity.getId())) {
            versionManageMapper.updateDate(versionManageEntity);
//            versionManageMapper.updateById(versionManageEntity);
        }

        return adapterConverter.versionManageEntityToProgress(versionManageEntity);
    }

    private Progress extend(VersionManageEntity versionManageEntity) {
        if (versionManageEntity == null) {
            return null;
        }

        List<VersionManageEntity> versionManageEntites = new ArrayList<>();
        versionManageEntites.add(versionManageEntity);
        List<Progress> progressList = this.extend(versionManageEntites);

        return progressList.get(0);
    }

    private List<Progress> extend(List<VersionManageEntity> versionManageEntites) {
        if (versionManageEntites.isEmpty()) {
            return new ArrayList<>();
        }

        List<Progress> progressList = new ArrayList<>();

        Set<Long> progressIds = new HashSet<>();
        Set<Long> projectIds = new HashSet<>();
        Set<Long> personIds = new HashSet<>();

        for (VersionManageEntity versionManageEntity : versionManageEntites) {
            Long projectId = versionManageEntity.getProjectId();
            if (projectId != null) {
                projectIds.add(projectId);
            }
            progressIds.add(versionManageEntity.getId());
            personIds.add(versionManageEntity.getCreatedUserId());
        }

        List<Project> projects = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(projectIds)) {
            projects = projectRepository.getProjectList(ProjectQuery.builder().ids(new ArrayList<>(projectIds)).build());
        }
        Map<Long, Project> idProjectMap = new HashMap<>();
        for (Project project : projects) {
            idProjectMap.put(project.getId(), project);
        }

        List<Person> people = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(personIds)) {
            people = personRepository.getPersonList(PersonQuery.builder().ids(new ArrayList<>(personIds)).build());
        }
        Map<Long, Person> idPeopleMap = new HashMap<>();
        for (Person application : people) {
            idPeopleMap.put(application.getId(), application);
        }

        for (VersionManageEntity versionManageEntity : versionManageEntites) {
            Progress progress = adapterConverter.versionManageEntityToProgress(versionManageEntity);
            progress.setProject(idProjectMap.getOrDefault(versionManageEntity.getProjectId(), new Project(versionManageEntity.getProjectId())));
            progress.setApplicant(idPeopleMap.getOrDefault(versionManageEntity.getCreatedUserId(), new Person(versionManageEntity.getCreatedUserId())));

            progressList.add(progress);
        }

        return progressList;
    }

    @Override
    public Page<Progress> getProgressKanBanPage(ProgressKanBanQuery progressKanBanQuery) {
        ResponseData<List<ProjectBasicResponse>> projectList = new ResponseData<>();
        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper;
        List<Map<String, Object>> list = new ArrayList<>();
        //判断有无主体院
        if (progressKanBanQuery.getMainCourtyard() == null) {
            projectList = progressProjectRepository.getProjectList(progressKanBanQuery.getHrOrganizationId());
        }
        if (progressKanBanQuery.getMainCourtyard() != null) {
            projectList = progressProjectRepository.getProjectList(progressKanBanQuery.getMainCourtyard());
        }
        if (projectList.getData().size() > 0) {
            lambdaQueryWrapper = new LambdaQueryWrapper<>();
            List<ProgressEntity> progressEntities = progressMapper.selectList(lambdaQueryWrapper);
            list = projectList.getData().stream().map(v -> {
                Map<String, Object> map = new HashMap<>();
                map.put(PROJECT_ID, v.getProjectId());
                map.put(PROJECT_Name, v.getProjectName());
                map.put(ENGINEER_TYPE, v.getProjectCategory());
                map.put(PROJECT_MANAGER, v.getProjectManager());
                map.put(ENGINEER_STATUS, v.getProjectStatus());
                Long id = v.getProjectId();
                boolean flag = true;
                if (progressEntities.size() > 0) {
                    for (ProgressEntity progressEntity : progressEntities) {
                        if (id.equals(progressEntity.getProjectId())) {
                            map.put(ID,progressEntity.getId());
                            LambdaQueryWrapper<ProgressDetailEntity> progressDetailEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            progressDetailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectScheduleId,progressEntity.getId());
                            progressDetailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectId,progressEntity.getProjectId());

                            progressDetailEntityLambdaQueryWrapper.and(wp -> {
                                wp.eq(ProgressDetailEntity::getCompletion, 0);
                                wp.or();
                                wp.ne(ProgressDetailEntity::getPercentage, "100");
                            });

                            List<ProgressDetailEntity> progressDetailEntityList = progressDetailMapper.selectList(progressDetailEntityLambdaQueryWrapper);
                            int lagTimeByTaskCount = 0;
                            for(ProgressDetailEntity t : progressDetailEntityList){
                                if(t.getLagTime() > lagTimeByTaskCount){
                                    lagTimeByTaskCount = t.getLagTime();
                                }
                            }
                            log.info("项目名称:{1}，滞后项目个数为:{2}，滞后时长为:{3}",v.getProjectName(),progressDetailEntityList.size(),lagTimeByTaskCount);
                            if(progressDetailEntityList.size() != 0 && lagTimeByTaskCount >0){
                                map.put(PROGRESS_STATUS, 0);
                            }else{
                                map.put(PROGRESS_STATUS, 1);
                            }
                            //map.put(PROGRESS_STATUS, progressEntity.getProgressStatus());
                            //map.put(LAG_TIME, progressEntity.getLagTime());
                            map.put(LAG_TIME, lagTimeByTaskCount);
                            map.put(SCHEDULE_START_TIME, progressEntity.getScheduleStartTime());
                            map.put(SCHEDULE_END_TIME, progressEntity.getScheduleEndTime());
                            map.put(REAL_START_TIME, progressEntity.getRealStartTime());
                            map.put(REAL_END_TIME, progressEntity.getRealEndTime());
                            map.put(PERCENTAGE, progressEntity.getPercentage());
                            this.extendPhotoFile(progressEntity,map);
                            flag = false;
                            break;
                        } else {
                            continue;
                        }
                    }
                }
                if (flag) {
                    map.put(ID,null);
                    map.put(PROGRESS_STATUS, 2);
                    map.put(LAG_TIME, 0);
                    map.put(SCHEDULE_START_TIME,null);
                    map.put(SCHEDULE_END_TIME, null);
                    map.put(REAL_START_TIME, null);
                    map.put(REAL_END_TIME, null);
                    map.put(PERCENTAGE, null);
                    map.put(PHOTO_FILE,null);
                }
                return map;
            }).collect(Collectors.toList());
            //条件排序
            List<Map<String, Object>> conditionSort = getConditionSort(list, progressKanBanQuery);
            //分页
            Page<Progress> progressPager = getPage(conditionSort, progressKanBanQuery.getOffset(), progressKanBanQuery.getPageSize());
            return progressPager;
        }
        return new Page<>();
    }

    //获取照片文件信息并填充
    private void extendPhotoFile(ProgressEntity progressEntity,Map<String, Object> map) {
        LambdaQueryWrapper<ProgressDetailEntity> lambdaQueryWrapperDetail = new LambdaQueryWrapper<>();
        lambdaQueryWrapperDetail.eq(ProgressDetailEntity::getProjectScheduleId,progressEntity.getId())
                .select(ProgressDetailEntity::getId);
        List<ProgressDetailEntity> progressDetailEntityList = projectScheduleDetaillMapper.selectList(lambdaQueryWrapperDetail);
        if (progressDetailEntityList.size()>0) {
            List<Long> progressDetailIds = progressDetailEntityList.stream().map(ProgressDetailEntity::getId).collect(Collectors.toList());
            LambdaQueryWrapper<ProjectAttachmentImageEntity> image = new LambdaQueryWrapper<>();
            image.in(ObjectUtils.isNotNull(progressDetailIds),ProjectAttachmentImageEntity::getProjectScheduleDetailId,progressDetailIds);
            List<ProjectAttachmentImageEntity> projectAttachmentImageEntities = projectAttachmentImageMapper.selectList(image);
            if (projectAttachmentImageEntities.size()>0){
                List<String> signKeys = projectAttachmentImageEntities.stream().map(ProjectAttachmentImageEntity::getSignKey).collect(Collectors.toList());
                List<File> fileList = fileRepository.getFileList(FileQuery.builder().signKeys(signKeys).build());
                List<FileResponse> fileResponseList = new ArrayList<>();
                fileList.forEach(o->{
                    fileResponseList.add( FileResponse.builder()
                            .name(o.getName())
                            .extName(o.getExtName())
                            .signKey(o.getSignKey())
                            .url(o.getUrlOut())
                            .build());
                });
                map.put(PHOTO_FILE,fileResponseList);
            }
        }
    }

    @Override
    public ProgressKanBanStatisticResponse getProgressKanStatisticBanPage(Long hrOrganizationId) {
        ResponseData<List<ProjectBasicResponse>> projectList = progressProjectRepository.getProjectList(hrOrganizationId);
        List<Long> ids = projectList.getData().stream().map(ProjectBasicResponse::getProjectId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)){
            return null;
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        int constructingProjectCount = 0;
        int stoppedProjectCount = 0;
        int lagProjectCount = 0;
        int yearCompletionProjectCount = 0;
        int monthCompletionProjectCount = 0;
        if (projectList.getData().size() > 0) {
            List<ProjectBasicResponse> data = projectList.getData();
            LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();

            lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(ids), ProgressEntity::getProjectId, ids);
            lambdaQueryWrapper.select(ProgressEntity::getProgressStatus, ProgressEntity::getRealEndTime, ProgressEntity::getId,ProgressEntity::getProjectId);
            List<ProgressEntity> progressEntities = progressMapper.selectList(lambdaQueryWrapper);


            for (ProjectBasicResponse projectBasicResponse : data) {
                if (EngieerStatusEnum.CONSTRUCTING.name().equals(projectBasicResponse.getProjectStatus())) {
                    constructingProjectCount++;
                }
                if (EngieerStatusEnum.STOPPED.name().equals(projectBasicResponse.getProjectStatus())) {
                    stoppedProjectCount++;
                }
            }
            if (progressEntities.size() > 0) {
                for (ProgressEntity progressEntity : progressEntities) {
                    LambdaQueryWrapper<ProgressDetailEntity> progressDetailEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    progressDetailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectScheduleId,progressEntity.getId());
                    progressDetailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectId,progressEntity.getProjectId());
                    progressDetailEntityLambdaQueryWrapper.and(wp -> {
                        wp.eq(ProgressDetailEntity::getCompletion, 0);
                        wp.or();
                        wp.ne(ProgressDetailEntity::getPercentage, "100");
                    });
                    progressDetailEntityLambdaQueryWrapper.select(ProgressDetailEntity ::getPercentage,ProgressDetailEntity::getStatus,ProgressDetailEntity::getCompletion,ProgressDetailEntity ::getLagTime);
                    List<ProgressDetailEntity> progressDetailEntityList = progressDetailMapper.selectList(progressDetailEntityLambdaQueryWrapper);
                    int lagTimeByTaskCount = 0;
                    for(ProgressDetailEntity t : progressDetailEntityList){
                        if(t.getLagTime() > lagTimeByTaskCount){
                            lagTimeByTaskCount = t.getLagTime();
                        }
                    }
                    if(progressDetailEntityList.size() > 0 && lagTimeByTaskCount > 0){
                        lagProjectCount++;
                    }
                    /*if (progressEntity.getProgressStatus() == 0) {
                        lagProjectCount++;
                    }*/
                    if (ObjectUtils.isNotNull(progressEntity.getRealEndTime()) && localDateTime.getYear() == progressEntity.getRealEndTime().getYear()) {
                        if (localDateTime.getMonth() == progressEntity.getRealEndTime().getMonth()) {
                            monthCompletionProjectCount++;
                        }
                        yearCompletionProjectCount++;
                    }
                }
            }
        }
        int constructionProjectCount = constructingProjectCount + stoppedProjectCount;
        ProgressKanBanStatisticResponse.ProgressKanBanStatisticResponseBuilder progressKanBanStatisticResponse = ProgressKanBanStatisticResponse.builder();
        progressKanBanStatisticResponse.constructingProject(constructingProjectCount)
                .constructionProject(constructionProjectCount)
                .LagProject(lagProjectCount)
                .stoppedProject(stoppedProjectCount)
                .yearCompletionProject(yearCompletionProjectCount)
                .monthCompletionProject(monthCompletionProjectCount);

        return progressKanBanStatisticResponse.build();
    }

    // 完工
    private  static  final  String  FINISHED ="FINISHED";
    // 竣工
    private  static  final  String  COMPLETED ="COMPLETED";


    @Override
    public List<Progress> getProgressKanLagProjectPage(Long hrOrganizationId) {
        ResponseData<List<ProjectBasicResponse>> projectList = progressProjectRepository.getProjectList(hrOrganizationId);
        // 排除 完工和竣工2种项目状态
        List<Long> ids = projectList.getData().stream().filter(projectBasicResponse -> !StrUtil.equalsAny(projectBasicResponse.getProjectStatus(),FINISHED,COMPLETED)).map(ProjectBasicResponse::getProjectId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)){
            return null;
        }
        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(ids), ProgressEntity::getProjectId, ids);
        lambdaQueryWrapper.eq(ProgressEntity::getProgressStatus, 0);
        lambdaQueryWrapper.gt(ProgressEntity ::getLagTime,30);//滞后时长大于30天
        lambdaQueryWrapper.select(ProgressEntity::getName, ProgressEntity::getLagTime,ProgressEntity ::getId,ProgressEntity::getProjectId);

        lambdaQueryWrapper.orderByDesc(ProgressEntity::getLagTime);
        List<ProgressEntity> progressEntityList = progressMapper.selectList(lambdaQueryWrapper);
        List<ProgressEntity> progressEntityListNew = new ArrayList<>();
        for(ProgressEntity entity : progressEntityList){
            LambdaQueryWrapper<ProgressDetailEntity> progressDetailEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            progressDetailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectScheduleId,entity.getId());
            progressDetailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectId,entity.getProjectId());

            progressDetailEntityLambdaQueryWrapper.and(wp -> {
                wp.eq(ProgressDetailEntity::getCompletion, 0);
                wp.or();
                wp.ne(ProgressDetailEntity::getPercentage, "100");
            });
            List<ProgressDetailEntity> progressDetailEntityList = progressDetailMapper.selectList(progressDetailEntityLambdaQueryWrapper);
            int lagTimeByTaskCount = 0;
            for(ProgressDetailEntity t : progressDetailEntityList){
                if(t.getLagTime() > lagTimeByTaskCount){
                    lagTimeByTaskCount = t.getLagTime();
                }
            }
            if(progressDetailEntityList.size() != 0 && lagTimeByTaskCount >30){
                entity.setLagTime(lagTimeByTaskCount);
                progressEntityListNew.add(entity);
            }
        }
        List<Progress> progressList = new ArrayList<>();
        if(progressEntityListNew.size() > 0){
            progressList = adapterConverter.progressEntityListToProgressList(progressEntityListNew);
        }
        return progressList;
    }

    @Override
    public List<ProcessTask> getProgressScheduleProcess(Long id) {
        List<ProcessTask> processList = processRemoteService.getProcessList(ProcessListQuery.builder()
                .businessType(CRANE)
                .businessCode(String.valueOf(id))
                .processDefinitionKey(PROCESS_VERSION).build());
        return processList;
    }

    @Override
    public void editVersionNullify(Long version, Long projectId) {
        LambdaQueryWrapper<VersionManageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(VersionManageEntity ::getProjectId,projectId);
        lambdaQueryWrapper.lt(VersionManageEntity ::getVersion,version);
        lambdaQueryWrapper.eq(VersionManageEntity ::getMainCourtyardApproval,1);
        List<VersionManageEntity> list = versionManageMapper.selectList(lambdaQueryWrapper);
        list.forEach(item ->{
            item.setMainCourtyardApproval(4l);
            item.setStatus(0l);
            versionManageMapper.updateById(item);
        });
    }

    @Override
    public List<Long> getVersionDownByVersionNoAndProjectId(Long version, Long projectId) {
        LambdaQueryWrapper<VersionManageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(VersionManageEntity ::getProjectId,projectId);
        lambdaQueryWrapper.lt(VersionManageEntity ::getVersion,version);
        lambdaQueryWrapper.eq(VersionManageEntity ::getMainCourtyardApproval,1);
        List<VersionManageEntity> list = versionManageMapper.selectList(lambdaQueryWrapper);
        List<Long> ids = new ArrayList<>();
        list.forEach(item ->{
            ids.add(item.getId());
        });
        return ids;
    }

    /**
     * @param listCondition
     * @param offset
     * @param pageSize
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.smedi.ismedi.progress.core.domain.aggregatemodel.Progress>
     * @description: 伪分页方法
     * @author liaojiajie
     * @date 2022/9/23 11:01
     */
    protected Page<Progress> getPage(List<Map<String, Object>> listCondition, Long offset, Long pageSize) {
        Pager<Map<String, Object>> mapPager = Pager.create(listCondition, pageSize.intValue());
        List<Map<String, Object>> pagedList = mapPager.getPagedList(offset.intValue());

        List<Progress> progressesList = new ArrayList<>();
        for (Map<String, Object> map : pagedList) {
            Progress progress = new Progress();
            if (ObjectUtils.isNotNull(map.get(ID))) {
                progress.setId(Long.valueOf(map.get(ID).toString()));
            }
            progress.setProjectId(Long.valueOf(map.get(PROJECT_ID).toString()));
            progress.setName(map.get(PROJECT_Name).toString());
            progress.setEngineerType(map.get(ENGINEER_TYPE).toString());
            progress.setGeneralManager(map.get(PROJECT_MANAGER).toString());
            progress.setEngineerStatus(map.get(ENGINEER_STATUS).toString());
            progress.setLagTime(Integer.parseInt(map.get(LAG_TIME).toString()));
            progress.setPhotoFile((ArrayList<FileResponse>)map.get(PHOTO_FILE));
            if (ObjectUtils.isNotNull(map.get(PROGRESS_STATUS))) {
                progress.setProgressStatus(Integer.parseInt(map.get(PROGRESS_STATUS).toString()));
            }
            if (ObjectUtils.isNotNull(map.get(SCHEDULE_START_TIME))) {
                progress.setScheduleStartTime((LocalDateTime) map.get(SCHEDULE_START_TIME));
            }
            if (ObjectUtils.isNotNull(map.get(SCHEDULE_END_TIME))) {
                progress.setScheduleEndTime((LocalDateTime) map.get(SCHEDULE_END_TIME));
            }
            if (ObjectUtils.isNotNull(map.get(REAL_START_TIME))) {
                progress.setRealStartTime((LocalDateTime) map.get(REAL_START_TIME));
            }
            if (ObjectUtils.isNotNull(map.get(REAL_END_TIME))) {
                progress.setRealEndTime((LocalDateTime) map.get(REAL_END_TIME));
            }
            if (ObjectUtils.isNotNull(map.get(PERCENTAGE))) {
                progress.setPercentage(map.get(PERCENTAGE).toString());
            }
            progressesList.add(progress);
        }

        int total = listCondition.size();
        double pagesDouble = Math.ceil(total / pageSize);
        long pages = Math.round(pagesDouble) + 1;

        Page<Progress> progressPager = new Page<>();
        progressPager.setPages(pages);
        progressPager.setCurrent(offset);
        progressPager.setSize(pageSize);
        progressPager.setTotal(total);
        progressPager.setRecords(progressesList);
        return progressPager;
    }

    /**
     * @param list
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @description: 条件排序方法
     * @author liaojiajie
     * @date 2022/9/23 11:08
     */
    protected List<Map<String, Object>> getConditionSort(List<Map<String, Object>> list,ProgressKanBanQuery progressKanBanQuery) {
        List<Map<String, Object>> listCondition = list.stream().filter(v ->
                v.get(PROJECT_MANAGER).toString().indexOf(progressKanBanQuery.getProjectManager()) > -1
        ).filter(v -> {
            if (progressKanBanQuery.getProjectId()!= null) {
                return progressKanBanQuery.getProjectId().equals(Long.valueOf(v.get(PROJECT_ID).toString()));
            }
            return true;
        }).filter(v -> {
            if (ObjectUtils.isNotNull(progressKanBanQuery.getProgressStatus())) {
                if (ObjectUtils.isNull(v.get(PROGRESS_STATUS))){
                    return false;
                }
                return progressKanBanQuery.getProgressStatus().equals(Integer.parseInt(v.get(PROGRESS_STATUS).toString()));
            }
            return true;
        }).filter(v -> {
            if (StringUtils.isNotBlank(progressKanBanQuery.getEngineerType())) {
                if (StringUtils.isBlank(v.get(ENGINEER_TYPE).toString())){
                    return false;
                }
                return progressKanBanQuery.getEngineerType().equals(v.get(ENGINEER_TYPE).toString());
            }
            return true;
        }).filter(v -> {
            if (StringUtils.isNotBlank(progressKanBanQuery.getYearCompletion())){
                if (ObjectUtils.isNull(v.get(REAL_END_TIME))){
                    return false;
                }
                return v.get(REAL_END_TIME).toString().indexOf(progressKanBanQuery.getYearCompletion().substring(0,4)) > -1;
            }
            return true;
        }).filter(v -> {
            if (progressKanBanQuery.getEngineerStatus().length > 0) {
                return ArrayUtils.contains(progressKanBanQuery.getEngineerStatus(),v.get(ENGINEER_STATUS).toString());
            }
            return true;
        }).collect(Collectors.toList());

        Collections.sort(listCondition, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return Integer.parseInt(o2.get(LAG_TIME).toString()) - Integer.parseInt(o1.get(LAG_TIME).toString());
            }
        });
        return listCondition;
    }

}
